// pages/me/login/login.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    codeUrl: '',
    username: '',
    password: '',
    code: '',
    uuid: '',
    token: '',
    openid: ''
  },

  //实时获取数据
  usernameInput:function (e) {
    this.setData({
      username: e.detail.value
    })
  },
  passwordInput:function (e) {
    this.setData({
      password: e.detail.value
    })
  },
  codeInput: function (e) {
  this.setData({
    code: e.detail.value
  })
},

  getCodeAndUuidUrl() {
    var that = this;
    app.sendGetRequest('/captchaImage',(res)=>{
      console.log(res);
      that.setData({
        codeUrl: "data:image/gif;base64," + res.img,
        uuid: res.uuid
      })
    })
  },

  doLogin() {
    var that = this;
    // 获取授权得到微信用户的信息
    // 构造 loginBody
    var data = {
      username: that.data.username,
      password: that.data.password,
      code: that.data.code,
      uuid: that.data.uuid
    };
    console.log(that.data.openid)
    if(that.data.openid == null) {
      // 没有 openid 非首次登录时
      that.login(data)
    } else {
      // 首次登录时
      wx.getUserProfile({
        desc: '用于完善用户资料',
        success(res){
          console.log('授权结果',res)
          var wxUser = {
            nickName:res.userInfo.nickName,
            sex:res.userInfo.gender,
            avatar:res.userInfo.avatarUrl,
            openid: that.data.openid,
            appId: app.getAppId()
          }
          data["wxUser"] = wxUser
          // 登录请求 
          that.login(data)
          
        },
        fail(res){
          console.log('授权失败',res)
        }
      })
    }
    
  },

  login(data) {
    app.sendPostRequest('/login',data,(res)=>{
      if(res.code == 200) {
        console.log(res);
        this.setData({
          token: res.token
        })
        app.setToken(res.token)
        wx.switchTab({
          url: '../../index/index',
        })
        wx.showToast({
          title: '登录成功',
        })
        // 登录成功后获取用户信息
        app.sendGetRequest('/wxGetInfo', (res) => {
          app.setUserInfo(res.user)
        })
      } else {
        wx.showToast({
          title: res.msg,
          // 加上  icon: 'none'  才能显示更多的字
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCodeAndUuidUrl()
    console.log(options.openid)
    this.data.openid = options.openid
  }
})


